import {
  addWebsiteTypeApi,
  updateWebsiteTypeApi,
  getWebsiteTypePaginationApi,
  getWebsitesPaginationApi,
  addAllWebsiteApi,
  updateWebsiteApi,
  getAllWebsiteTypesByConditionApi,
  deleteWebsiteApi
} from '@/services'
import { pick } from 'lodash'
import { Button, Card, Form, Icon, Image, InputText, Message, Modal, Page, Select, Table, Text, Typography } from 'magic-ui-react'
import { ModalHandle } from 'magic-ui-react/dist/Modal/interface'
import { ActionType, ColumnType, TableBaseType } from 'magic-ui-react/dist/Table/interface'
import { useEffect, useRef, useState } from 'react'
import styles from './styles.module.less'
import { TableDataType } from './types'

const WebsitesList = () => {

  const modalRef = useRef<ModalHandle>()
  const actionRef = useRef<ActionType>()

  const [form] = Form.useForm()

  const [title, setTitle] = useState('')
  const [options, setOptions] = useState([])

  const columns: ColumnType<TableDataType>[] = [
    {
      title: '图标',
      dataKey: 'iconUrl',
      width: 100,
      bodyCellRender: (column, record, index) => {
        return (
          <Image width={40} height={40} src={record.iconUrl} />
        )
      },
    },
    {
      title: '名称',
      dataKey: 'title'
    },
    {
      title: '地址',
      dataKey: 'url',
      bodyCellRender: (column, record, index) => {
        return (
          <Text
            underline
            type="primary"
            className='hover:cursor-pointer'

            onClick={() => {
              window.open(record.url)
            }}
          >
            {record.url}
          </Text>
        )
      },
    },
    {
      title: '描述',
      dataKey: 'description',
      bodyCellRender: (_column, record, index) => {
        return (
          <div className='text-ellipsis-2' title={record.description}>
            {record.description}
          </div>
        )
      },
    },
    {
      title: '创建时间',
      dataKey: 'createdTime',
      width: 200,
    },
    {
      title: '更新时间',
      dataKey: 'updateTime',
      width: 200,
    },
    {
      title: '操作',
      width: 200,
      dataKey: 'operation',
      bodyCellRender: (_columns, record) => {
        return (
          <div className='flex gap10'>
            <Button
              type='primary'
              onClick={() => {
                setTitle('编辑')
                modalRef.current?.open()

                setTimeout(() => {
                  form.setFieldsValue({ ...record })
                }, 0)
              }}
            >编辑</Button>
            <Button
              status='error'
              onClick={() => {
                setTitle('删除')
                deleteItem(record)
              }}
            >删除</Button>
          </div>
        )
      }
    },
  ]

  const onOK = async () => {
    try {
      const requestData = form.getFields()
      if (requestData._id) {
        await updateWebsiteApi(
          requestData._id,
          pick(requestData, ['title', 'url', 'iconUrl', 'description', 'type'])
        );
      } else {
        await addAllWebsiteApi(requestData as any);
      }
      modalRef.current?.close()
      actionRef.current?.refresh()
    } catch (error) {
    }
  }


  const deleteItem = async (record: any) => {
    try {
      await deleteWebsiteApi([record._id])
      Message.success('删除成功');
      actionRef.current?.refresh()
    } catch (error) {

    }
  }

  const getOptions = async () => {
    try {
      let res = await getAllWebsiteTypesByConditionApi()
      let newOptions = res.data.map((item: any) => {
        return {
          label: item.name,
          value: item._id,
        }
      })
      setOptions(newOptions)
    } catch (error) {

    }
  }

  useEffect(() => {
    getOptions()
  }, [])

  return (
    <Page className={styles.WebsitesList}>
      <Table
        search={{
          columns: [
            {
              formItem: {
                name: 'title',
                label: '名称'
              },
              type: 'text'
            },
          ]
        }}
        oprationContent={(
          <Card borders={[]}>
            <div className='flex'>
              <Button
                type='primary'
                icon={<Icon icon="add" />}
                onClick={() => {
                  setTitle('添加')
                  modalRef.current?.open()
                }}
              >
                添加
              </Button>
            </div>
          </Card>
        )}
        actionRef={actionRef}
        borderWidth={0}
        columns={columns}
        data={async (pagination, search) => {
          let list: any[] = []
          try {
            const res: any = await getWebsitesPaginationApi({
              ...pagination,
              ...search,
            });
            list = res.data

            return {
              list,
              total: res.total!,
            }
          } catch (error) {

          }
        }}
        pagination={{
          sort: ['page'],
        }}
      />
      <Modal title={title} onOK={onOK} ref={modalRef}>
        <Form
          form={form}
          layout='vertical'
        >
          <Form.Item label="名称" name='title'>
            <InputText />
          </Form.Item>
          <Form.Item label="地址" name='url'>
            <InputText />
          </Form.Item>
          <Form.Item label="图标地址" name='iconUrl'>
            <InputText />
          </Form.Item>
          <Form.Item label="描述" name='description'>
            <InputText />
          </Form.Item>
          <Form.Item label="类型" name='type'>
            <Select
              options={options}
            />
          </Form.Item>
        </Form>
      </Modal>
    </Page>
  )
}
export default WebsitesList